<?php


namespace App\Request;


use App\Exceptions\BasicException;

class Validator
{
    //命名尽量做到：见名知意，没有歧义，不易冲突
    //例如礼物名称不要直接叫name，而是gift_name
    const RULE = [
        'date_tag' => 'integer|in:-1,0,1,3,7,30',
        'start_date' => 'required_if:date_tag,0|date_format:Y-m-d',
        'end_date' => 'required_if:date_tag,0|date_format:Y-m-d',
    ];

    //参数验证
    public static function paramVerify($targetFields, $actualParams)
    {
        //获取验证规则
        $rule = self::getValidateRule($targetFields);
        //验证
        $v = app('validator')->make($actualParams, $rule);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());
    }

    //获取验证规则
    private static function getValidateRule($targetParams)
    {
        $rule = [];
        foreach ($targetParams as $targetParam) {
            if (isset(self::RULE[$targetParam])) {
                $rule[$targetParam] = self::RULE[$targetParam];
            }
        }
        return $rule;
    }
}
